package com.coolwen.controller;

import com.coolwen.entity.User;
import com.coolwen.service.RoleService;
import com.coolwen.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: 弓赛鹏
 * @create: 2021-09-17 14:39
 * @description: 注册页面
 */
@Controller
@RequestMapping("/register")
public class RegisterController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register(Model model) {
        model.addAttribute(new User());

        return "redirect:/register/add";
    }

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public String add(Model model) {
        model.addAttribute("user", new User());
        model.addAttribute("roles", roleService.listRole());
        return "register/add";
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public String add(User user, HttpServletRequest req, Model model) {
        String[] trids = req.getParameterValues("rids");
        List<Long> rids = new ArrayList<Long>();
        for (String rid : trids) {
            rids.add(Long.parseLong(rid));
        }
        userService.add(user, rids);
        return "redirect:/login/login";
    }




}
